package com.casic.pengxh.ndk.base

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.OutputStream
import java.security.InvalidParameterException


abstract class SerialPortActivity : AppCompatActivity() {

    private val kTag = "SerialPortActivity"
    lateinit var out: OutputStream

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(initLayoutView())
        setupTopBarLayout()
        initData(savedInstanceState)
        observeRequestState()
        initEvent()

        try {
            val serialPorts = BaseApplication.get().getSerialPorts()
            //读
            lifecycleScope.launch(Dispatchers.IO) {
                serialPorts?.apply {
                    val stream = this[0].inputStream
                    while (isActive) {
                        try {
                            val buffer = ByteArray(64)
                            val size = stream.read(buffer)
                            if (size > 0) {
                                withContext(Dispatchers.Main) {
                                    onDataReceived(buffer)
                                }
                            }
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            lifecycleScope.launch(Dispatchers.IO) {
                serialPorts?.apply {
                    val stream = this[1].inputStream
                    while (isActive) {
                        try {
                            val buffer = ByteArray(64)
                            val size = stream.read(buffer)
                            if (size > 0) {
                                withContext(Dispatchers.Main) {
                                    onDataReceived(buffer)
                                }
                            }
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            Toast.makeText(this, "串口已打开！", Toast.LENGTH_SHORT).show()
            Log.d(kTag, "onCreate => 串口已打开！")

            //写
            serialPorts?.apply {
                out = this[0].outputStream
            }
        } catch (e: SecurityException) {
            Toast.makeText(this, "您没有串口的读写权限！", Toast.LENGTH_SHORT).show()
        } catch (e: IOException) {
            Toast.makeText(this, "因为不明原因，串口无法打开！", Toast.LENGTH_SHORT).show()
        } catch (e: InvalidParameterException) {
            Toast.makeText(this, "请检查串口！", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 初始化xml布局
     */
    abstract fun initLayoutView(): Int

    /**
     * 特定页面定制沉浸式状态栏
     */
    abstract fun setupTopBarLayout()

    /**
     * 初始化默认数据
     */
    abstract fun initData(savedInstanceState: Bundle?)

    /**
     * 数据请求状态监听
     */
    abstract fun observeRequestState()

    /**
     * 初始化业务逻辑
     */
    abstract fun initEvent()

    /**
     * 串口读数
     * */
    abstract fun onDataReceived(buffer: ByteArray)

    override fun onDestroy() {
        BaseApplication.get().closeSerialPort()
        super.onDestroy()
    }
}